package cn.com.joco.dk.core.tools;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpRequest {

	public static Map<String, String> Get(String url) {
		return JsonUtils.ParseJsonToMap(HttpRequest(url));
	}

	public static String HttpRequest(String url) {
		BufferedReader reader = null;
		StringBuilder stringBuilder = new StringBuilder();
		try {
			URL getUrl = new URL(url);
			HttpURLConnection connection = (HttpURLConnection) getUrl
					.openConnection();
			connection.connect();
			reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			String lines = "";
			while ((lines = reader.readLine()) != null) {
				stringBuilder.append(lines);
			}
			connection.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
				}
			}
		}
		return stringBuilder.toString();
	}

	public static Map<String, String> Post(String url,
			Map<String, String> paramMap) {
		HttpPost httpost = new HttpPost(url);
		try {
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			if(paramMap != null){
				for (String key : paramMap.keySet()) {
					params.add(new BasicNameValuePair(key, paramMap.get(key)));
				}
			}
			httpost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
			// 请求
			HttpResponse response = new DefaultHttpClient().execute(httpost);
			// 处理响应
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 正常返回
				// 读取xml文档
				String result = EntityUtils.toString(response.getEntity());
				return JsonUtils.ParseJsonToMap(result);
			} else {
				System.err.println("error");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		httpost.releaseConnection();
		return null;
	}
}
